<?php
/**
 * 物品放行模块微站定义
 *
 * @author 橙橙同学
 * @url 
 */
defined('IN_IA') or exit('Access Denied');

load()->model('mc');
load()->func('communication');
load()->func('file');

class Orange_articledeliveryModuleSite extends WeModuleSite {

    const MEDIAGET = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=';
    private $return = array(
        'errCode'=>0,
        'msg'=>'',
        'data'=>''
    );



    public function doMobileDevCommonTipsSuccess()
    {
        $this->template('commontips/success');
    }

    public function doMobileDevCommonTipsError()
    {
        $this->template('commontips/error');
    }

    public function doMobileDevDeliveryCertificate()
    {
        $this->template('articledelivery/certificate');
    }

    public function doMobileDevDeliveryRecord()
    {
        $this->template('articledelivery/record');
    }

    public function doMobileDevArticleDeliveryApply()
    {
        include $this->template('articledelivery/apply');
    }

    /**
     * @param $uniacid
     * @return array|mixed
     * @author: 橙橙同学
     * @fun:获取accessToken
     */
    protected function getAccessToken($uniacid){
        $weiObj = WeAccount::create($uniacid);
        $token = $weiObj->fetch_token();
        return $token;
    }


    /**
     * @return bool
     * @author:橙橙同学
     * @func:上传图片接口
     */
    public function doMobileSaveMediaByMediaId()
    {
        global $_W,$_GPC;
        $media_id = $_GPC['media_id'];
        if(!empty($media_id)){
            $link = '&media_id=';
            $url = self::MEDIAGET.$this->getAccessToken($_W['uniacid']).$link.$media_id;
            $response = ihttp_get($url);
            print_r($response['content']); // 输出百度页面Html
            //TODO...


        }else{
            $this->return['errCode'] = -1;
            $this->return['msg'] = 'media_id不能为空';
        }
        echo json_encode($this->return);
    }


    public function doMobileJssdk()
    {
        include $this->template('jssdk');
    }

	public function doMobileEntry() {
		//这个操作被定义用来呈现 功能封面
        load()->func('tpl');
        include $this->template('index');
	}

    /**
     * @author:橙橙同学
     * @func:检查基本微信环境
     */
	protected function checkWeiEnvironment()
    {
        global $_W;
        if(empty($_W['openid']))
        {
            echo "未查询到您的openid";
            exit();
        }
    }

    /**
     * @author:橙橙同学
     * @func:判空
     */
	protected function checkEmptyFields($data,$fields)
    {
        $emptyFields = array();
        foreach ($data as $key=>$value){
            if(empty($value)){
                $this->return['errCode'] = -1;
                $this->return['msg'] = $fields[$key].'不能为空';
                echo json_encode($this->return);
                exit();
            }
        }
    }

    /**
     * @author:橙橙同学
     * @func:物品放行记录列表
     */
    public function doMobileArticleDeliveryRecordList()
    {
        global $_W,$_GPC;
        $uid = mc_openid2uid($_W['openid']);

        $todyTime = strtotime(date('Y-m-d'));
        $startTime = $todyTime-(3600*7*24);

        if(!empty($uid)){

            //查询最近七天的申请记录
            $articleDeliveryRecord = pdo_fetchall("select * from ".tablename('articledelivery_applyrecord')."
            where `uniacid`=:uniacid and `uid`=:uid create_time between {$startTime} and {$todyTime}",array(
                ':uniacid'=>$_W['uniacid'],':uid'=>$uid
            ));
            //TODO..根据申请记录的状态排序渲染模板  status=1 待审核 status=2未使用 status=3 已使用 status=4 已过期
        }
    }

    protected function getMemberInfoByUid($uid)
    {
        global $_W;
        $memberInfo = pdo_fetch("select * from ".tablename('mc_members')." where `uniacid`=:uniacid
        and `uid`=:uid",array('uniacid'=>$_W['uniacid'],'uid'=>$uid));
        return $memberInfo;
    }


    /**
     * @author:橙橙同学
     * @func:申请物品放行API
     */
	public function doMobileApplyArticleDelivery()
    {
        global $_W,$_GPC;

        $start_time = strtotime($_GPC['start_time']);
        $end_time = strtotime($_GPC['end_time']);
        $sponsor_name = isset($_GPC['sponsor_name'])?trim($_GPC['sponsor_name']):'';
        $sponsor_platenumber = isset($_GPC['sponsor_platenumbe'])?trim($_GPC['sponsor_platenumbe']):'';
        $articlepic = isset($_GPC['articlepic'])?$_GPC['articlepic']:'';

        $data = array(
            'sponsor_name'=>$sponsor_name,
            'sponsor_platenumber'=>$sponsor_platenumber,
            'start_time'=>$start_time,
            'end_time'=>$end_time,
            'articlepic'=>$_GPC['articlepic'],
        );
        $fields = array(
            'sponsor_name'=>'发起者',
            'sponsor_platenumber'=>'车牌号',
            'start_time'=>'开始时间',
            'end_time'=>'结束时间',
            'articlepic'=>'物品照片',
        );
        //检测字段空的情况
        $this->checkEmptyFields($data,$fields);

        $uid = mc_openid2uid($_W['openid']);
        if(!empty($uid)){
            $memberInfo = $this->getMemberInfoByUid($uid);
            //企业会员身份判断
            if($memberInfo['groupid']==3){
                //是会员并且是企业会员
                $insertData = array(
                    'uid'=>intval($uid),
                    'articlepic'=>$articlepic,
                    'start_time'=>$start_time,
                    'end_time'=>$end_time,
                    'sponsor_name'=>$sponsor_name,
                    'sponsor_platenumber'=>$sponsor_platenumber,
                    'create_time'=>time(),
                    'uniacid'=>$_W['uniacid']
                );
                //插入数据
                $res = pdo_insert(tablename('articledelivery_applyrecord'),$data);
                if($res){
                    $this->return['msg'] = '申请成功，等待审核';
                }else{
                    $this->return['errCode'] = -1;
                    $this->return['msg'] = '申请失败，请重试';
                }
            }else{
                $this->return['errCode'] = -1;
                $this->return['msg'] = '会员非企业会员，不可使用此功能';
            }

        }else{
            $this->return['errCode'] = -1;
            $this->return['msg'] = '会员信息不合法';
        }
        echo json_encode($this->return);
    }


    /**
     * @author:橙橙同学
     * @func:物品放行审核
     */
    public function doWebCheckDeliveryApply(){
        global $_GPC,$_W;
        //错误标记
        $errmsg = '';
        $op = $_GPC['op']?$_GPC['op']:'display';
        $return = array(
            'errCode'=>0,
            'msg'=>''
        );
        switch ($op){
            // 申请
            case 'display':
                $uid = $_GPC['uid'];
                //articledelivery_applyrecord 主键ID
                $applyid = $_GPC['applyid'];
                if(!empty($uid) && !empty($applyid)){
                    $memberInfo = $this->getMemberInfoByUid($uid);
                    //是会员并且是企业会员
                    if($memberInfo['groupid']==3) {
                        //查询会员申请通行记录
                        $deliveryApplyRecord = pdo_fetch("SELECT * FROM " . tablename('articledelivery_applyrecord') . " 
        WHERE `uniacid`=:uniacid and `uid`=:uid and `id`=:id", array(':uid'=>$uid,':uniacid'=>$_W['uniacid'],':id'=>$applyid));
                        //防范
                        if(empty($deliveryApplyRecord)){
                            $errmsg = '未查询到此申请记录 请核实!';
                        }
                    }else{
                        $errmsg = '该会员身份非企业会员 请核实!';
                    }
                }else{
                    $errmsg = '未获取到物品放行申请信息';
                }
                include $this->template('articledeliverymanage/checkdeliveryapply');
                break;
                //审核
            case 'check':
                $uid = $_GPC['uid'];
                $id = $_GPC['id'];

                //审核 1待审核-》2未使用
                $data = array(
                    'status'=>2
                );
                $res = pdo_update('articledelivery_applyrecord',$data,array('id'=>$id,'uid'=>$uid));
                //TODO 这里要记录ims_articledelivery_checkrecord 审核记录 暂时不确定是给后台还是给前台 先做~
                if($res){
                    $return['msg'] = '审核通过';
                }else{
                    $return['errCode'] = -1;
                    $return['msg'] = '审核失败';
                }
                echo json_encode($return);
                exit();
                break;
            default:
                $return['errCode'] = -1;
                $return['msg'] = '非法请求';
                echo json_encode($return);
        }
    }


	public function doWebArticleDeliveryManage($where = "") {
        global $_GPC,$_W;
        $op = $_GPC['op']?$_GPC['op']:'display';
        $return = array(
            'errCode'=>0,
            'msg'=>''
        );

        if($_GPC['token'] == $_W['token'] && $_GPC['submit']!=''){
            //搜索
            $value = trim($_GPC['keyword']);
            $where = "and value like '%{$value}%'";
        }else{
            $where = '';
        }

        switch ($op){
            // 申请
            case 'apply':
                $pindex = max(1, intval($_GPC["page"]));
                $psize = 5;
                $list = pdo_fetchall("SELECT * FROM " . tablename('articledelivery_applyrecord') . " 
               
                WHERE `uniacid`=:uniacid  {$where} ORDER BY id DESC LIMIT " . ($pindex - 1) * $psize . ',' . $psize, array(':uniacid'=>$_W['uniacid']));

                $total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('articledelivery_applyrecord') . " 
                WHERE uniacid = '{$_W['uniacid']}' {$where}");
                $pager = pagination($total, $pindex, $psize, $url = '', $context = array('before' => 2, 'after' => 2, 'ajaxcallback' => ''));
                break;
            case 'display':

                break;
            default:
        }
        include $this->template('articledeliverymanage/articledeliverymanage');
	}
	public function doWebArticledeliverylog() {
		//这个操作被定义用来呈现 管理中心导航菜单
	}
	public function doMobileIndexnav() {
		//这个操作被定义用来呈现 微站首页导航图标
	}
	public function doMobilePersonalnav() {
		//这个操作被定义用来呈现 微站个人中心导航
	}
	public function doMobileQknav() {
		//这个操作被定义用来呈现 微站快捷功能导航
	}

}